package CommentApi.Output;

import CommentApi.Comments.MethodComment;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Data
public class UriInfo {
    private String[] uris;
    private RequestMethod[] requestMethod;
    private String[] headers;
    private String[] consumes;
    private String[] produces;
    private MethodComment methodComment;

    public UriInfo(String[] roots,MethodComment methodComment){
        getRequestMappingUri(methodComment.getMethod(), roots);
        this.methodComment = methodComment;
    }
    @SneakyThrows
    private void getRequestMappingUri(Method method, String[] rootUris){
        RequestMapping requestMappingOn = AnnotationUtils.getAnnotation(method, RequestMapping.class);
        String[] headers  = new String[0];
        String[] consumes = new String[0];
        String[] produces = new String[0];
        String[] paths = new String[0];
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
        if (requestMapping == null){
            for (Annotation annotation : method.getAnnotations()) {
                final Class<? extends Annotation> type = annotation.annotationType();

                if (type.getAnnotation(RequestMapping.class) != null) {
                    //优先value
                    paths = getMappingAttribute(annotation, "value");
                    if (paths.length == 0){
                        paths = getMappingAttribute(annotation, "path");
                    }
                    headers = getMappingAttribute(annotation, "headers");
                    consumes = getMappingAttribute(annotation, "consumes");
                    produces = getMappingAttribute(annotation, "produces");
                    break;
                }
            }
        }else {
            paths = requestMapping.value();
        }


        if (paths.length == 0){
            throw new RuntimeException(method+"缺少uri信息");
        }

        final String[] uris = new String[paths.length * rootUris.length];
        int i = 0;
        for (String rootUri : rootUris) {
            for (String methodUri : paths) {
                uris[i++] = rootUri+methodUri;
            }
        }
        this.uris = uris;
        this.requestMethod = requestMappingOn.method();
        this.consumes = consumes;
        this.headers = headers;
        this.produces = produces;
    }
    @SneakyThrows
    private String[] getMappingAttribute(Annotation annotation,String attributeName){
        return (String[]) annotation.getClass().getDeclaredMethod(attributeName).invoke(annotation);
    }



}
